import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
  ArrowLeft,
  RefreshCw,
  Download,
  Filter,
  Search,
  Calendar,
  AlertCircle,
  CheckCircle,
  Clock
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/Card'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { Badge } from '../components/ui/Badge'
import { Switch } from '../components/ui/Switch'
import { Alert, AlertDescription } from '../components/ui/Alert'

interface AuditPageProps {
  authFetch: (url: string, options?: RequestInit) => Promise<Response>
}

function useAudit(limit: number, authFetch: (url: string, options?: RequestInit) => Promise<Response>) {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  
  async function load() {
    setLoading(true)
    setError(null)
    try {
      const res = await authFetch(`/admin/audit?limit=${encodeURIComponent(String(limit))}`)
      if (!res.ok) {
        if (res.status === 401) {
          throw new Error('Authentication required')
        }
        throw new Error(`HTTP ${res.status}`)
      }
      const data = await res.json()
      setItems(data.items || [])
    } catch (e: any) {
      setError(e?.message || 'Failed to load audit')
    } finally {
      setLoading(false)
    }
  }
  
  useEffect(() => { load() }, [limit])
  return { items, loading, error, reload: load }
}

export function AuditPage({ authFetch }: AuditPageProps) {
  const { t } = useTranslation()
  const [limit, setLimit] = useState(100)
  const [allowed, setAllowed] = useState<'all' | 'allowed' | 'denied'>('all')
  const [pluginQ, setPluginQ] = useState('')
  const [autoRefresh, setAutoRefresh] = useState(false)
  const { items, loading, error, reload } = useAudit(limit, authFetch)

  useEffect(() => {
    if (!autoRefresh) return
    const id = setInterval(reload, 5000)
    return () => clearInterval(id)
  }, [autoRefresh, reload])

  const filtered = items.filter((it) => {
    const okAllowed = allowed === 'all' ? true : allowed === 'allowed' ? !!it.allowed : !it.allowed
    const okPlugin = pluginQ ? String(it.plugin || '').includes(pluginQ) : true
    return okAllowed && okPlugin
  })

  const stats = {
    total: items.length,
    allowed: items.filter(i => i.allowed).length,
    denied: items.filter(i => !i.allowed).length,
    recent: items.filter(i => {
      const itemTime = new Date(i.ts).getTime()
      const fiveMinutesAgo = Date.now() - 5 * 60 * 1000
      return itemTime > fiveMinutesAgo
    }).length
  }

  const exportAuditLog = async () => {
    try {
      const res = await authFetch('/admin/audit?format=csv')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      
      const blob = await res.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `audit-log-${new Date().toISOString().split('T')[0]}.csv`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (error: any) {
      console.error('Failed to export audit log:', error)
    }
  }

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Link to="/admin">
            <Button variant="ghost">
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t('audit.backToAdmin')}
            </Button>
          </Link>
          <div className="h-6 w-px bg-border" />
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{t('audit.title')}</h1>
            <p className="text-muted-foreground mt-1">
              {t('audit.subtitle')}
            </p>
          </div>
        </div>
        
        <div className="flex items-center space-x-3">
          <Button
            variant="outline"
            onClick={exportAuditLog}
            className="flex items-center space-x-2"
          >
            <Download className="h-4 w-4" />
            <span>{t('audit.export')}</span>
          </Button>

          <Button
            onClick={reload}
            disabled={loading}
            loading={loading}
            className="flex items-center space-x-2"
          >
            <RefreshCw className="h-4 w-4" />
            <span>{t('audit.refresh')}</span>
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('audit.stats.totalEvents')}</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">
              {t('audit.stats.allRecordedEvents')}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('audit.stats.allowed')}</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.allowed}</div>
            <p className="text-xs text-muted-foreground">
              {t('audit.stats.successfulOperations')}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('audit.stats.denied')}</CardTitle>
            <AlertCircle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.denied}</div>
            <p className="text-xs text-muted-foreground">
              {t('audit.stats.blockedOperations')}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('audit.stats.recent')}</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.recent}</div>
            <p className="text-xs text-muted-foreground">
              {t('audit.stats.lastFiveMinutes')}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle>{t('audit.filters.title')}</CardTitle>
          <CardDescription>
            {t('audit.filters.subtitle')}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col lg:flex-row gap-4">
            {/* Search */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder={t('audit.filters.searchPlaceholder')}
                  value={pluginQ}
                  onChange={(e) => setPluginQ(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            {/* Limit */}
            <div className="flex items-center space-x-2">
              <label className="text-sm font-medium whitespace-nowrap">{t('audit.filters.limit')}:</label>
              <Input
                type="number"
                min={1}
                max={1000}
                value={limit}
                onChange={(e) => setLimit(Number(e.target.value))}
                className="w-20"
              />
            </div>

            {/* Filter by status */}
            <div className="flex items-center space-x-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <select
                value={allowed}
                onChange={(e) => setAllowed(e.target.value as any)}
                className="input w-32"
              >
                <option value="all">{t('audit.filters.allStatus')}</option>
                <option value="allowed">{t('audit.filters.allowed')}</option>
                <option value="denied">{t('audit.filters.denied')}</option>
              </select>
            </div>

            {/* Auto refresh */}
            <Switch
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
              label={t('audit.filters.autoRefresh')}
            />
          </div>
        </CardContent>
      </Card>

      {/* Audit Log */}
      <Card>
        <CardHeader>
          <CardTitle>{t('audit.log.title')}</CardTitle>
          <CardDescription>
            {t('audit.log.showing', { filtered: filtered.length, total: items.length })}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {error ? (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          ) : (
            <div className="border rounded-lg">
              <div className="max-h-96 overflow-auto">
                <table className="w-full text-sm">
                  <thead className="bg-muted/50 sticky top-0">
                    <tr>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.timestamp')}</th>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.plugin')}</th>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.method')}</th>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.status')}</th>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.resource')}</th>
                      <th className="text-left p-3 font-medium">{t('audit.log.columns.error')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map((it, idx) => (
                      <tr key={idx} className="border-t hover:bg-muted/25">
                        <td className="p-3 whitespace-nowrap text-xs font-mono">
                          {new Date(it.ts).toLocaleString()}
                        </td>
                        <td className="p-3">
                          <Badge variant="outline">{it.plugin || t('audit.log.system')}</Badge>
                        </td>
                        <td className="p-3 font-mono text-xs">{it.method}</td>
                        <td className="p-3">
                          <Badge variant={it.allowed ? 'default' : 'destructive'}>
                            {it.allowed ? t('audit.log.status.allowed') : t('audit.log.status.denied')}
                          </Badge>
                        </td>
                        <td className="p-3 max-w-xs">
                          <pre className="text-xs whitespace-pre-wrap break-words">
                            {JSON.stringify(it.resource, null, 2)}
                          </pre>
                        </td>
                        <td className="p-3 max-w-xs">
                          {it.error && (
                            <pre className="text-xs text-destructive whitespace-pre-wrap break-words">
                              {JSON.stringify(it.error, null, 2)}
                            </pre>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {filtered.length === 0 && (
                  <div className="text-center py-8 text-muted-foreground">
                    {loading ? t('audit.log.loading') : t('audit.log.noLogs')}
                  </div>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
